package com.netpace.iem.umair.dal;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.netpace.iem.umair.model.*;

@Repository
public class ExpenseMemory implements IExpenseDao {
	private List<Expense> expenses;

	// Default constructor is for Main memory Db
	public ExpenseMemory() {
		this.expenses = new ArrayList<Expense>();
	}
	
	@Override
	public void insert(Expense expense){
		expenses.add(expense);
	}

	@Override
	public void update(Expense expense, int pk) {
		int index = getIndex(pk); 
		if ( index != -1 ) {
			expenses.remove(index);
			expenses.add(index, expense);
		}
	}
	
	@Override
	public void delete(Expense expense, int pk) {
		int index = getIndex(expense); 
		if ( index != -1 ) {
			expenses.remove(index);
		}
	}
	
	@Override
	public void delete(int pk) {
		int index = getIndex(pk); 
		if ( index != -1 ) {
			expenses.remove(index);
		}
	}
	
	@Override
	public Expense findById(int pk) {
		int index = getIndex(pk); 
		
		if ( index != -1 ) {
			return expenses.get(index);
		}
		
		return null;
	}
	
	@Override
	public List<Expense> findAll(){
		return expenses;
	}
	
	private int getIndex(Expense expense) {
		if ( expenses.contains(expense) ) 
			return expenses.indexOf(expense);
		else
			return -1;
	}
	
	private int getIndex(int pk) {
		for (int i = 0; i < expenses.size(); i++) {
			if ( expenses.get(i).getId() == pk ) {
				return i;
			}
		}
		
		return -1;
	}
}
